package com.gitee.slowcreator.http.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.mime.MimeType;
import org.apache.tika.mime.MimeTypes;

import java.nio.charset.Charset;

/**
 * @author zxw
 * @date 2023/6/10 20:38
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class FileNameUtil {

    /**
     * 获取原始文件名
     * 文件名从 header 的 Content-Disposition 中解析出来 有两种形式
     * attachment; filename=xxx.xxx
     * attachment; filename*="UTF-8''xxx.xx"
     *
     * @param contentDisposition Content-Disposition 参数
     * @param url                请求url
     * @return
     */
    public static String getOriginFileNameFromContentDisposition(String contentDisposition, String url) {

        String filename = "";
        if (StrUtil.isNotBlank(contentDisposition)) {
            String[] strings = contentDisposition.split(";");
            if (strings.length > 1) {
                filename = strings[1];
                // 两种文件名的形式
                filename = filename.replace("filename=", "");
                filename = filename.replace("filename*=\"UTF-8''", "");
                // 将以下的字符去除
                filename = StrUtil.removeAll(filename, ' ', '\\', '/', '\"');
                filename = URLDecoder.decode(filename, Charset.defaultCharset());
            } else {
                filename = "";
            }
        } else {
            // 从url中解析出文件名
            if (StrUtil.isNotBlank(url)) {
                int index = StrUtil.indexOf(url, '?');
                if (index != -1) {
                    url = StrUtil.sub(url, 0, index);
                }
                index = StrUtil.lastIndexOf(url, "/", url.length(), false);
                if (index != -1 && !StrUtil.endWith(url, "/")) {
                    String fn = StrUtil.sub(url, index + 1, url.length());
                    if (StrUtil.contains(url, ".")) {
                        filename = fn;
                    }
                }
            }
        }

        return filename;
    }

    /**
     * 获取新的文件名
     *
     * @param originFileName 原始文件名
     * @return
     */
    public static String getNewFileName(@NonNull String originFileName) {

        String mainName = FileUtil.mainName(originFileName);
        String extName = FileUtil.extName(originFileName);
        extName = StrUtil.isBlank(extName) ? "" : "." + extName;

        return StrUtil.join("", mainName, "_", IdUtil.getSnowflake().nextIdStr(), extName);
    }

    public static String getExtNameFromContentType(String contentType) {

        if (StrUtil.isBlank(contentType) || StrUtil.contains(contentType, "application/octet-stream")) {
            // application/octet-stream 流类型获取不到实际类型
            log.info("ContentType为空或为application/octet-stream,获取后缀名失败.");
            return "";
        }

        try {
            MimeTypes mimeTypes = MimeTypes.getDefaultMimeTypes();
            MimeType mimeType = mimeTypes.forName(contentType);
            return mimeType.getExtension();
        } catch (Exception e) {
            log.error("获取ContentType:{},后缀名失败,返回空扩展名.", contentType);
            return "";
        }
    }

    public static void main(String[] args) {

        String url = "https://dl.hdslb.com/mobile/fixed/bili_win/bili_win-install.exe?v=1.10.1&spm_id_from=333.47.b_646f776e6c6f61642d6c696e6b.9";
        int index = StrUtil.indexOf(url, '?');
        if (index != -1) {
            url = StrUtil.sub(url, 0, index);
        }
        index = StrUtil.lastIndexOf(url, "/", url.length(), false);
        if (index != -1 && !StrUtil.endWith(url, "/")) {
            String fn = StrUtil.sub(url, index + 1, url.length());
            if (StrUtil.contains(url, ".")) {
                System.out.println(fn);
            }
        }
    }
}
